package uia.alumni.profile;

import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import uia.alumni.data.CvEntry;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Command;



/**
 *
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class DeleteCvEntry extends Command implements Constants {
    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "profile.deletecventry";

    @PersistenceUnit(name=PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    @Resource
    private UserTransaction tx;


    public DeleteCvEntry() {
        super(Role.member);
    }


    /**
     * Delete a cv entry (specified by the parameter CVENTRY)
     * from the database.
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter(CVENTRY);
        long cveId = parseLong(id, -1);

        try {
            tx.begin();
            EntityManager em = emf.createEntityManager();
            User user = getLoggedInUser(em, request);

            CvEntry cve = user.getCvEntry(cveId);
            if (cve != null) user.removeCvEntry(cve);
            tx.commit();
        }
        catch (Exception e) {
            addMessage(request, "CV Entry was not deleted, because: "
                    +e.getMessage());
        }
        forwardTo(EditCv.SERVLET_NAME, request, response);
    }

    public final static long serialVersionUID = 1;

}
